package com.mrd.frame.quartz;

import java.io.Serializable;
import java.util.Collection;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mrd.frame.domain.NoticeMessage;
import com.mrd.frame.domain.OrderInteraction;
import com.mrd.frame.onlinepay.PayNotice;
import com.mrd.frame.redis.JedisClientClusterImpl;
import com.mrd.frame.service.OrderInteractionService;
import com.mrd.weixinpay.util.Constents;

@Component("resendMessageTask")
public class ResendMessageTask implements Job, Serializable {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(ResendMessageTask.class);

	@Autowired
	private OrderInteractionService orderInteractionService;
	@Autowired
	private JedisClientClusterImpl jedisClientClusterImpl;
	@Autowired
	private PayNotice payNotice;
	
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		// 获取发送失败的异步通知
		@SuppressWarnings("unchecked")
		Collection<String> keys = jedisClientClusterImpl.keys(Constents.PAYNOTICEINDEX+"*");
		if(keys != null){
			logger.info("异步通知重发，通知队列长度："+keys.size());
			for(String key : keys){
				NoticeMessage noticeMessage = jedisClientClusterImpl.get(key, NoticeMessage.class);
				// 重新发送
				boolean result = payNotice.excute(noticeMessage);
				OrderInteraction record = new OrderInteraction(noticeMessage.getOrderId(),"A7",noticeMessage.noticeMessageToJson().toString());
				if(result){
					//重发成功，从redis中删除
					jedisClientClusterImpl.delete(key);
				} else {
					record.setStatus("1");
				}
				//记录信息到数据库
				orderInteractionService.insert(record);
			}
		}
	}

}
